package medium.合并区间;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 56. 合并区间
 * 创建时间：2024-03-27 10:53
 * 地址：
 */
public class 合并区间_56 {
    public static void main(String[] args) {
        int[][] nums=new int[][]{{1,3},{2,6},{8,10},{14,25}};
        System.out.println(Arrays.deepToString(merge(nums)));
    }
    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(i -> i[0]));
        int[][] rsl = new int[intervals.length][2];
        int index = -1;
        for (int[] interval : intervals) {
            // 当前区间的起始位置 > 结果的最后区间
            if (index < 0 || interval[0] > rsl[index][1]) {
                rsl[++index] = interval;
            } else {
                rsl[index][1] = Math.max(rsl[index][1], interval[1]);
            }
        }
        return Arrays.copyOf(rsl, index + 1);
    }


}
